<template>
  <div class="app-container">
    <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
             style="margin-top: 20px">
      <el-tag color="#2b85e4" style="color:white;margin-bottom:20px" size="large">
        基本信息
      </el-tag>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="产品名称" prop="insuranceName" :label-width="formLabelWidth">
            <el-input v-model="formData.insuranceName" style="width:300px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行业" :label-width="formLabelWidth" prop="name">
            <el-select v-model="formData.industryIds" placeholder="请选择" no-data-text="暂无数据"
                       style="width:300px" multiple>
              <el-option
                v-for="item in allIndustry"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="产品类型" prop="insuranceClassifyId" :label-width="formLabelWidth">
            <el-select v-model="formData.insuranceClassifyId" style="width:300px" @change="insuranceClassifyChange">
              <el-option
                v-for="item in allInsuranceClassify"
                :value="item.id"
                :key="item.id"
                :label="item.insuranceClassifyName">

              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售价" prop="insuranceSalePrice" :label-width="formLabelWidth">
            <el-input-number v-model="formData.insuranceSalePrice" :precision="2" :step="0.01"
                             style="width:280px"></el-input-number>
            元
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="成本价" prop="insuranceCostPrice" :label-width="formLabelWidth">
            <el-input-number v-model="formData.insuranceCostPrice" :precision="2" :step="0.01"
                             style="width:280px"></el-input-number>
            元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="承保保险公司" prop="insuranceCompanyId" :label-width="formLabelWidth">
            <el-select v-model="formData.insuranceCompanyId" style="width:300px">
              <el-option
                v-for="item in allInsuranceCompany"
                :value="item.id"
                :key="item.id"
                :label="item.insuranceCompanyName">

              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="保险服务提供商" prop="insuranceProviderId" :label-width="formLabelWidth">
            <el-select v-model="formData.insuranceProviderId" style="width:300px">
              <el-option
                v-for="item in allInsuranceServiceSupplier"
                :value="item.id"
                :key="item.id"
                :label="item.companyName">

              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高赔付金额" prop="highestCompensateAmount" :label-width="formLabelWidth">
            <el-input-number v-model="formData.highestCompensateAmount" :precision="2" :step="0.01"
                             style="width:270px"></el-input-number>
            万元
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="免赔金额" prop="deductionAmount" :label-width="formLabelWidth">
            <el-input-number v-model="formData.deductionAmount" :precision="2" :step="0.01"
                             style="width:270px"></el-input-number>
            元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效距离" prop="effectiveRange" :label-width="formLabelWidth">
            <el-input-number v-model="formData.effectiveRange" :precision="2" :step="0.01"
                             style="width:270px"></el-input-number>
            公里
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="有效时间" prop="effectiveTime" :label-width="formLabelWidth">
            <el-input-number v-model="formData.effectiveTime" :precision="0" :step="1"
                             style="width:270px"></el-input-number>
            小时
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单通知模板" prop="orderNotifyMessageTemplateId" :label-width="formLabelWidth">
            <el-select v-model="formData.orderNotifyMessageTemplateId" style="width:300px">
              <el-option
                v-for="item in allMessageTemplate"
                :value="item.id"
                :key="item.id"
                :label="item.messageTemplateName">

              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="照片上传约束" prop="password" :label-width="formLabelWidth">
            <el-checkbox-group v-model="uploadConstraintArr" @change="checkChange">
              <el-checkbox label="pz">是否可拍照</el-checkbox>
              <el-checkbox label="xc">是否可从相册选取</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.insuranceClassifyId=='e7cec11e64a7459e8d096a706458d1f8'||formData.insuranceClassifyId=='21be70cd31a547c38bfc09552a71db08'">
          <el-form-item label="意外医疗费" prop="accidentMedicineAmount" :label-width="formLabelWidth">
            <el-input-number v-model="formData.accidentMedicineAmount" :precision="2" :step="0.01"
                             style="width:270px"></el-input-number>
            万元
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="销售方式" :label-width="formLabelWidth" prop="sellMethod">
            <el-select v-model="formData.sellMethod" style="width:300px">
              <el-option value="0" key="0" label="销售"></el-option>
              <el-option value="1" key="1" label="赠送"></el-option>
              <el-option value="2" key="2" label="可销售可赠送"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务协议" :label-width="formLabelWidth" prop="protocol">
            <el-input type="textarea" v-model="formData.protocol" auto-complete="off" style="width:300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tag color="#2b85e4" style="color:white;margin-bottom:10px;margin-top:10px" size="large">
        分成策略
      </el-tag>
      <div style="margin-top:10px;margin-bottom: 10px">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="addStrategyData">新增</el-button>
        <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteStrategyAny">删除</el-button>
      </div>
      <el-table
        :data="this.formData.dividedStrategy"
        border
        empty-text="暂无数据"
        style="width: 100%"
        @selection-change="handleStrategySelectionChange">
        <el-table-column
          type="selection"
          width="35">
        </el-table-column>
        <el-table-column
          label="服务商"
          property="roleName">
        </el-table-column>
        <el-table-column
          label="分成"
          property="shared">
        </el-table-column>
        <el-table-column
          label="积分"
          property="integral">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="success"
              @click="editStrategyData(scope.$index, scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col :span="24" style="margin-top: 20px">
          <el-button type="success" @click="handleAdd('ruleForm')" v-if="actionType=='add'" :loading="loading">立即创建
          </el-button>
          <el-button type="success" @click="handleEdit('ruleForm')" v-else :loading="loading">修改</el-button>

        </el-col>
      </el-row>
    </el-form>
    <el-dialog :title="actionStrategyType=='add'?'新增分成策略':'分成策略'" :visible.sync="dialogStrategyBFormVisible" top="10vh"
               width="55%">
      <el-form :model="strategyFormData" ref="operationRuleForm">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="服务商" :label-width="formLabelWidth">
              <el-select v-model="strategyFormData.role" placeholder="请选择" style="width:300px"
                         @change="roleSelectChange" :disabled="actionStrategyType=='edit'">
                <el-option
                  v-for="item in allServiceProdiver"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="金额分成" :label-width="formLabelWidth">
              <el-input-number v-model="strategyFormData.shared" :precision="2" :step="0.01"
                               style="width:300px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="积分分成" :label-width="formLabelWidth">
              <el-input-number v-model="strategyFormData.integral" :precision="0" :step="1"
                               style="width:300px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStrategyBFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleStrategyAdd" v-if="actionStrategyType=='add'" :loading="loading">保存
        </el-button>
        <el-button type="primary" @click="handleStrategyEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }

  .m-col {
    border: 1px solid #ebeef5;
    border-bottom: none;
    padding-left: 10px;
    height: 40px;
    line-height: 40px;
    color: #909399;
    font-weight: 500;
    font-size: 12px;
  }

  .m-col-left {
    border: 1px solid #ebeef5;
    border-left: none;
    border-bottom: none;
    padding-left: 10px;
    height: 40px;
    line-height: 40px;
    font-size: 12px;
  }

  .m-col-bottom {
    border: 1px solid #ebeef5;
    padding-left: 10px;
    height: 250px;
    line-height: 250px;
    color: #909399;
    font-weight: 500;
    font-size: 12px;
  }

  .m-col-bottom-left {
    border: 1px solid #ebeef5;
    border-left: none;
    padding-left: 10px;
    height: 250px;
    overflow-y: auto;
    font-size: 12px;
  }
</style>

<script>

  import insuranceClassifyApi from '@/api/insuranceClassifyApi'
  import insuranceInfoApi from '@/api/insuranceInfoApi'
  import insuranceCompanyApi from '@/api/insuranceCompanyApi'
  import insuranceServiceSupplierApi from '@/api/insuranceServiceSupplierApi'
  import messageTemplateApi from '@/api/messageTemplateApi'
  import industryApi from '@/api/industryApi'

  export default {
    name: 'insuranceProductDetail',
    created() {
      //获取当前tag
      this.setCurrentTag()
      messageTemplateApi.listAll((res) => {
        this.allMessageTemplate = res
      }, () => {
      })

      industryApi.listAll((res) => {
        this.allIndustry = res
      }, () => {
      })
      if (this.actionType == 'add') {
        insuranceClassifyApi.listAll((res) => {
          this.allInsuranceClassify = res
          insuranceCompanyApi.listAll((res1) => {
            this.allInsuranceCompany = res1
            insuranceServiceSupplierApi.listAll((res2) => {
              this.allInsuranceServiceSupplier = res2
            }, () => {
            })
          }, () => {
          })
        }, () => {
        })
      } else {
        insuranceClassifyApi.listAll((res) => {
          this.allInsuranceClassify = res
          insuranceCompanyApi.listAll((res1) => {
            this.allInsuranceCompany = res1
            insuranceServiceSupplierApi.listAll((res2) => {
              this.allInsuranceServiceSupplier = res2
              this.getData()
            }, () => {
            })

          }, () => {
          })

        }, () => {
        })
      }
    },
    data() {
      return {
        rules: {
          insuranceName: [
            {required: true, message: '请输入产品名称', trigger: 'blur'}
          ],
          orderNotifyMessageTemplateId: [
            {required: true, message: '请选择订单通知模板', trigger: 'change'}
          ],
          insuranceClassifyId: [
            {required: true, message: '请选择产品类型', trigger: 'change'}
          ],
          insuranceSalePrice: [
            {required: true, message: '请输入售价', trigger: 'change'}
          ],
          insuranceCostPrice: [
            {required: true, message: '请输入成本价', trigger: 'change'}
          ],
          insuranceProviderId: [
            {required: true, message: '请选择承保保险公司', trigger: 'change'}
          ],
          insuranceCompanyId: [
            {required: true, message: '请选择保险服务提供商', trigger: 'change'}
          ],
          highestCompensateAmount: [
            {required: true, message: '请输入最高赔付金额', trigger: 'change'}
          ],
          deductionAmount: [
            {required: true, message: '请输入免赔金额', trigger: 'change'}
          ],
          protocol: [
            {required: true, message: '请输入服务协议', trigger: 'blur'}
          ],
          sellMethod: [
            {required: true, message: '请选择销售方式', trigger: 'change'}
          ]
        },
        allMessageTemplate: [],
        allServiceProdiver: [
          {
            id: '811f820613394fc481612a47282e5f8f',
            name: '救援司机'
          },
          {
            id: 'e300c4bd7df24fa3a57955893f349965',
            name: '救援公司'
          },
          {
            id: '73630d394fcb4a6dbc38c43284b0e23d',
            name: '救援代理'
          }
        ],
        allInsuranceServiceSupplier: [],
        allInsuranceCompany: [],
        dialogStrategyBFormVisible: false,
        actionStrategyType: 'add',
        handleId: '',
        strategyFormData: {
          role: '',
          roleName: '',
          shared: '',
          integral: ''
        },
        multipleStrategySelection: [],
        allIndustry: [],
        formData: {
          insuranceCompanyId: '',
          insuranceProviderId: '',
          insuranceClassifyId: '',
          insuranceName: '',
          insuranceSalePrice: '',
          insuranceCostPrice: '',
          orderNotifyMessageTemplateId: '',
          dividedStrategy: [],
          uploadConstraint: {
            is_taking_pictures: 0,
            is_photo: 0
          },
          highestCompensateAmount: 0,
          deductionAmount: 0.00,
          accidentMedicineAmount: 0,
          effectiveRange: 0,
          effectiveTime: 0,
          publicStatus: '1',
          sellMethod: '',
          industryIds: []
        },
        allInsuranceClassify: [],
        loading: false,
        id: this.$route.query.id,
        actionType: this.$route.params.type,
        formLabelWidth: '130px',
        uploadConstraintArr: [],
        allTag: [],
        currentTag: {},
      }
    },
    methods: {
      setCurrentTag() {
        this.allTag = this.$store.state.tagsView.visitedViews
        console.log(this.allTag)
        for (var lt of this.allTag) {
          if (lt.name == this.$route.name) {
            this.currentTag = lt;
            break
          }
        }
      },
      insuranceClassifyChange(value) {
        for (var aic of this.allInsuranceClassify) {
          if (value === aic.id) {
            this.formData.orderNotifyMessageTemplateId = aic.messageTemplateId
            this.formData.dividedStrategy = aic.dividedStrategy
            this.formData.protocol = aic.protocol
            this.initUploadConstraint(aic.uploadConstraint)
          }
        }
      },
      initUploadConstraint(uploadConstraint) {
        this.uploadConstraintArr = []
        if (uploadConstraint.is_photo == '1') {
          this.uploadConstraintArr.push('xc')
          this.formData.uploadConstraint.is_photo = '1'
        } else {
          this.formData.uploadConstraint.is_photo = '0'
        }

        if (uploadConstraint.is_taking_pictures == '1') {
          this.uploadConstraintArr.push('pz')
          this.formData.uploadConstraint.is_taking_pictures = '1'
        } else {
          this.formData.uploadConstraint.is_taking_pictures = '0'
        }
      },
      checkChange(value) {
        if (value.indexOf('pz') != -1) {
          this.formData.uploadConstraint.is_taking_pictures = '1'
        } else {
          this.formData.uploadConstraint.is_taking_pictures = '0'
        }

        if (value.indexOf('xc') != -1) {
          this.formData.uploadConstraint.is_photo = '1'
        } else {
          this.formData.uploadConstraint.is_photo = '0'
        }
      },
      roleSelectChange(v) {
        for (var o of this.allServiceProdiver) {
          if (o.id == v) {
            this.strategyFormData.role = o.id
            this.strategyFormData.roleName = o.name
            break
          }
        }
      },
      handleAdd() {
        if (this.uploadConstraintArr.length == 0) {
          this.$message({
            message: '请选择照片上传约束',
            type: 'warning'
          })
          return
        }
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            insuranceInfoApi.add(this.formData, (res) => {
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.actionType = 'edit'
              this.id = res
              //this.handleCompleteStepBtn()
            }, () => {
            })
          }
        })
      },
      getData() {
        insuranceInfoApi.get(this.id, (res) => {
          this.formData = res
          this.initUploadConstraint(this.formData.uploadConstraint)
        }, () => {
        })
      },
      handleEdit() {
        if (this.uploadConstraintArr.length == 0) {
          this.$message({
            message: '请选择照片上传约束',
            type: 'warning'
          })
          return
        }
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            insuranceInfoApi.update(this.id, this.formData, (res) => {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
            }, () => {
            })
          }
        })
      },
      addStrategyData() {
        this.strategyFormData = {
          role: '',
          roleName: '',
          shared: '',
          integral: ''
        }
        this.actionStrategyType = 'add'
        this.dialogStrategyBFormVisible = true
      },
      handleStrategyAdd() {
        if (this.checkStrategy(this.strategyFormData.role)) {
          this.$message({
            type: 'warning',
            message: '该服务商角色已添加!'
          })
          return
        }
        this.formData.dividedStrategy.push(this.strategyFormData)
        this.dialogStrategyBFormVisible = false
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
      },
      checkStrategy(role) {
        for (var sf of this.formData.dividedStrategy) {
          if (sf.role == role) {
            return true
          }
        }
        return false
      },
      editStrategyData(index, row) {
        for (const s of this.formData.dividedStrategy) {
          if (s.role === row.role) {
            this.handleId = row.role
            let qqstrategyFormData = {
              role: '',
              roleName: '',
              shared: '',
              integral: ''
            }
            qqstrategyFormData.role = s.role
            qqstrategyFormData.roleName = s.roleName
            qqstrategyFormData.shared = s.shared
            qqstrategyFormData.integral = s.integral
            this.strategyFormData = qqstrategyFormData
            this.actionStrategyType = 'edit'
            this.dialogStrategyBFormVisible = true
            break
          }
        }
      },
      handleStrategyEdit() {
        let index = 0;
        for (const s of this.formData.dividedStrategy) {
          if (s.role === this.handleId) {
            this.formData.dividedStrategy.splice(index, 1)
            this.formData.dividedStrategy.push(this.strategyFormData)
            this.dialogStrategyBFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            break
          }
          index++
        }
      },
      handleStrategySelectionChange(val) {
        this.multipleStrategySelection = []
        for (var ms of val) {
          this.multipleStrategySelection.push(ms.role)
        }
      },
      deleteStrategyAny() {
        if (this.multipleStrategySelection.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (const m of this.multipleStrategySelection) {
            let i = 0
            for (const s of this.formData.dividedStrategy) {
              if (s.role === m) {
                this.formData.dividedStrategy.splice(i, 1)
                break
              }
              i++
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleCompleteStepBtn() {
        console.log(this.currentTag)
        this.$store.dispatch('delVisitedView', this.currentTag).then((views) => {
          console.log(this.currentTag)
          if (this.isActive(this.currentTag)) {
            console.log(this.currentTag)
            const latestView = views.slice(-1)[0]
            if (latestView) {
              this.$router.push(latestView)
            } else {
              this.$router.push('/')
            }
          }
        })
      },
      isActive(route) {
        return route.path === this.$route.path
      },
    }
  }
</script>
